package com.slf.engine.services.impl;

import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import com.slf.engine.base.IBaseDao;
import com.slf.engine.bo.Order;
import com.slf.engine.common.SysContants;
import com.slf.engine.common.SysContext;
import com.slf.engine.http.HttpClientManager;
import com.slf.engine.services.IBossService;
import com.slf.engine.services.IBusService;
import com.slf.engine.services.IEVCService;
import com.slf.engine.services.IHpBossService;
import com.slf.engine.services.helper.ServiceHelper;
import com.slf.engine.utils.Factory;

/**
 * 
 * @author ZhangDong
 * @version 2.0
 * @category 交易业务处理类
 *
 */
public class BusServiceImpl implements IBusService {

	private static final Logger log = Logger.getLogger(BusServiceImpl.class);
	
	/**
	 * 获取一笔订单
	 * @return
	 */
	public Order getOneOrder()
	{
		synchronized (SysContext.ORDER_LIST) {
			if(SysContext.ORDER_LIST.size() > 0)
			{
				Order order =  SysContext.ORDER_LIST.get(0);
				SysContext.ORDER_LIST.remove(order);
				return order;
			}
		}
		return null;
	}
	
	/**
	 * 交易处理类
	 */
	public Order doService(Order order,HttpClientManager manager)
	{
		//进行交易处理
		SysContext.FREE_TIME = System.currentTimeMillis();
		IEVCService connService = new EVCServiceImpl();
		order = connService.doPay(order, manager, false);
		if(order.getClbz() == SysContants.CZ_RUN)
		{
			//放入缓存队列
			ServiceHelper.putToCache(order);
			return null;
		}
		return order;
	}
	
	/**
	 * 通知结果返回
	 */
	public void doNoticeResult(Order order)
	{
		log.log(Priority.INFO, "正在返回充值结果orderId:" + order.getOrderId() + " clbz:" + order.getClbz() + " cljg:" + order.getCljg());
		IBossService bossService = new BossServiceImpl();
//		IHpBossService bossService = new HpbossServiceImpl();
		IBaseDao baseDao = (IBaseDao)Factory.getInstantBiz("baseDao");
		if(bossService.doBack(order))
		{
			//通知成功
			order.setTzbz(SysContants.CZ_SUCCESS);
		}else{
			//通知失败
			if(order.getTzcs() <= SysContants.MAX_NOTICE_NUM)
			{
				ServiceHelper.putToNotice(order);
			}else{
				order.setTzbz(SysContants.CZ_FAILURE);
			}
		}
		try {
			baseDao.modify(order, "noticBack");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "通知结果提交数据库库失败:" + e.getMessage());
		}
		
	}

	/**
	 * 充值结果记录
	 */
	public void doBusResult(Order order) {
		// TODO Auto-generated method stub
		IBaseDao baseDao = (IBaseDao)Factory.getInstantBiz("baseDao");
		try {
			log.log(Priority.INFO, "记录交易结果order_id:" + order.getOrderId() + " account:" + order.getAccount() + 
					" money:" + order.getMoney() + " clbz:" + order.getClbz() + " cljg:" + order.getCljg());
			baseDao.modify(order, "backOrder");
			ServiceHelper.putToNotice(order);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "数据库记录充值结果异常" + e.getMessage());
		}
	}
}
